package com.lmx.healthcode.ui.activity;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;


import com.lmx.healthcode.R;
import com.lmx.healthcode.base.MyApp;
import com.lmx.healthcode.common.base.BaseActivity;
import com.lmx.healthcode.model.bean.Student;
import com.lmx.healthcode.util.CommonUtil;
import com.lmx.healthcode.util.SharedPreUtil;
import com.lmx.healthcode.util.ToastUtil;

import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

/**
 * @author Leung
 * @date 2020/9/9 21:58
 */
public class DataActivity extends BaseActivity {

    @BindView(R.id.img_menu)
    ImageView imgMenu;
    @BindView(R.id.et_studentId)
    EditText etStudentId;
    @BindView(R.id.et_studentName)
    EditText etStudentName;
    @BindView(R.id.sp_college)
    Spinner spCollege;
    @BindView(R.id.et_studentClass)
    EditText etStudentClass;
    @BindView(R.id.et_counselor)
    EditText etCounselor;
    @BindView(R.id.et_counselor_phone)
    EditText etCounselorPhone;
    @BindView(R.id.sp_dormitories)
    Spinner spDormitories;
    @BindView(R.id.rb_1)
    RadioButton rb1;
    @BindView(R.id.rb_2)
    RadioButton rb2;
    @BindView(R.id.rg_type)
    RadioGroup rgType;
    @BindView(R.id.tv_startTime)
    TextView tvStartTime;
    @BindView(R.id.tv_endTime)
    TextView tvEndTime;
    @BindView(R.id.sp_doors)
    Spinner spDoors;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    private Student student;

    @Override
    public int getLayoutId() {
        return R.layout.activity_data;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        if (!MyApp.isFirstCommit()) {
            getLocal();
        }
    }

    @OnClick({R.id.tv_startTime, R.id.tv_endTime, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_startTime:
            case R.id.tv_endTime:
                CommonUtil.showTimePicker(this).show(view);
                break;
            case R.id.btn_submit:
                submit();
                break;
            default:
        }
    }

    private void submit() {
        if (getInputData()) {
            student.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e == null) {
                        ToastUtil.showToast("数据提交成功！");
                        // 保存当前信息的id
                        SharedPreUtil.saveString(DataActivity.this, SharedPreUtil.KEY_OBJECT_ID, student.getObjectId());
                        // 判断是否是第一次提交
                        if (MyApp.isFirstCommit()) {
                            SharedPreUtil.saveBoolean(DataActivity.this, SharedPreUtil.KEY_FIRST_COMMIT, false);
                        }
                        // 保存信息到本地
                        SharedPreUtil.saveLocal(DataActivity.this, student);
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        ToastUtil.showToast("数据提交失败！" + e);
                    }
                }
            });
        }

    }

    /**
     * 获取用户输入信息
     *
     * @return 是否获取成功
     */
    private boolean getInputData() {
        String studentId = etStudentId.getText().toString().trim();
        if (TextUtils.isEmpty(studentId)) {
            ToastUtil.showToast("宝贝，您的学号未填呢！");
            return false;
        }

        String studentName = etStudentName.getText().toString().trim();
        if (TextUtils.isEmpty(studentName)) {
            ToastUtil.showToast("宝贝，您的姓名未填呢！");
            return false;
        }

        String college = spCollege.getSelectedItem().toString();

        String studentClass = etStudentClass.getText().toString().trim();
        if (TextUtils.isEmpty(studentClass)) {
            ToastUtil.showToast("宝贝，您的班级未填呢！");
            return false;
        }

        String counselor = etCounselor.getText().toString().trim();
        if (TextUtils.isEmpty(counselor)) {
            ToastUtil.showToast("宝贝，您的辅导员未填呢！");
            return false;
        }

        String counselorPhone = etCounselorPhone.getText().toString().trim();
        if (TextUtils.isEmpty(counselorPhone)) {
            ToastUtil.showToast("宝贝，您的辅导员电话未填呢！");
            return false;
        }

        String dormitory = spDormitories.getSelectedItem().toString();

        String type;
        if (rgType.getCheckedRadioButtonId() == R.id.rb_1) {
            type = "住宿";
        } else {
            type = "走读";
        }

        long startTime = (long) tvStartTime.getTag();
        SharedPreUtil.saveLong(this, SharedPreUtil.KEY_START_TIME, startTime);
        long endTime = (long) tvEndTime.getTag();
        SharedPreUtil.saveLong(this, SharedPreUtil.KEY_END_TIME, endTime);
        String outSchoolTime = CommonUtil.formatDate("HH:mm", startTime) + "-" +
                CommonUtil.formatDate("HH:mm", endTime);

        String outSchoolDoor = spDoors.getSelectedItem().toString();

        student = new Student(
                Integer.valueOf(studentId),
                studentName,
                college,
                studentClass,
                counselor,
                Long.valueOf(counselorPhone),
                dormitory,
                type,
                outSchoolTime,
                outSchoolDoor
        );
        return true;
    }

    /**
     * 获取本地学生信息
     */
    private void getLocal() {
        Student student = SharedPreUtil.getLocal(this);
        etStudentId.setText(String.format(Locale.CHINA, "%d", student.getStudentId()));
        etStudentName.setText(student.getName());
        spCollege.setSelection(CommonUtil.isCollege(student.getCollege()));
        etStudentClass.setText(student.getStudentClass());
        etCounselor.setText(student.getCounselor());
        etCounselorPhone.setText(String.format(Locale.CHINA, "%d", student.getCounselorPhone()));
        spDormitories.setSelection(CommonUtil.isDormitory(student.getDormitory()));
        rgType.getChildAt(CommonUtil.isType(student.getType())).setClickable(true);
        String[] time = CommonUtil.parseTime(student.getOutSchoolTime());
        if (time.length == 2) {
            tvStartTime.setText(time[0]);
            tvStartTime.setTag(SharedPreUtil.getLong(this, SharedPreUtil.KEY_START_TIME, 0L));
            tvEndTime.setText(time[1]);
            tvEndTime.setTag(SharedPreUtil.getLong(this, SharedPreUtil.KEY_END_TIME, 0L));
        }
        spDoors.setSelection(CommonUtil.isOutSchoolDoor(student.getOutSchoolDoor()));
    }

}
